<template>
  <a-spin :spinning='confirmLoading'>
    <j-form-container :disabled='formDisabled'>
      <!-- 主表单区域 -->
      <a-form :form='form' slot='detail'>
        <a-row>
          <a-col :span='12'>
            <a-form-item label='报销编号' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="['code']" placeholder='系统自动生成' disabled></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='申请人' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="['createBy']" disabled />
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='申请时间' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-date v-decorator="['createTime']" :showTime='false' dateFormat='YYYY-MM-DD' style='width: 100%'
                      disabled />
            </a-form-item>
          </a-col>
          <!-- <a-col :span="12" >
            <a-form-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-select-depart v-decorator="['sysOrgCode']" customReturnField="orgCode" disabled/>
            </a-form-item>
          </a-col> -->
          <a-col :span='12'>
            <a-form-item label='报销类别' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-dict-select-tag type='list' v-decorator="['type',validatorRules.type]" :trigger-change='true'
                                 dictCode='hf_oa_reimbursement_type' placeholder='请选择报销类别' @change='typeChange' />
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='费用所属' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-dict-select-tag type='list' v-decorator="['auditGrade',validatorRules.auditGrade]"
                                 :trigger-change='true' dictCode='audit_grade' placeholder='请选择报销分类' />
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='金额合计' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="['total', {initialValue:0}]" placeholder='金额合计' style='width: 100%' type='number'
                       precision='2' disabled>
                <span slot='addonAfter'>元</span>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12' v-if="typeDictText==='1' || model.opportunityId">
            <a-form-item label='商机名称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-popup
                v-decorator="['opportunityName',validatorRules.opportunityName]"
                :trigger-change='true'
                org-fields='id,name,customer_name,num'
                dest-fields='opportunityId,opportunityName,shortName,opportunityNum'
                code='bus_business_opportunity_select'
                @callback='popupCallback'
                :param='{saleLeader: $store.getters.userInfo.realname}'
              />
              <a-input v-decorator="['opportunityId']" v-show='false'></a-input>
            </a-form-item>
          </a-col>

          <a-col :span='12' v-else-if="typeDictText==='2' || model.projectId||typeDictText==='11'">
            <a-form-item label='项目名称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-popup
                v-decorator="['projectName',validatorRules.projectName]"
                :trigger-change='true'
                org-fields='id,short_name,customer_name'
                dest-fields='projectId,projectName,shortName'
                code='pm_project_select'
                @callback='popupCallback'
              />
              <input v-decorator="['projectId']" v-show='false'></input>
            </a-form-item>
          </a-col>
          <a-col :span='12'
                 v-if="typeDictText==='1'|| typeDictText==='11'|| typeDictText==='2' || model.opportunityId || model.projectId">
            <a-form-item label='客户简称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="['shortName']" disabled></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12' v-if='model.bpmStatus == "3"'>
            <a-form-item label='已发放' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-switch v-decorator="['issue']"></j-switch>
            </a-form-item>
          </a-col>
          <!--          <a-col :span="24">-->
          <!--            <a-form-item label="备注" :labelCol="labelCol2" :wrapperCol="wrapperCol2">-->
          <!--              <a-textarea v-decorator="['remark']" rows="3" placeholder="请输入备注" />-->
          <!--            </a-form-item>-->
          <!--          </a-col>-->
        </a-row>
      </a-form>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model='activeKey' @change='handleChangeTabs'>
      <a-tab-pane tab='报销单项目' :key='refKeys[0]' :forceRender='true'>
        <j-editable-table
          :ref='refKeys[0]'
          :loading='oaReimbursementItemsTable.loading'
          :columns='oaReimbursementItemsTable.columns'
          :dataSource='oaReimbursementItemsTable.dataSource'
          :maxHeight='300'
          :disabled='formDisabled'
          :rowNumber='true'
          :rowSelection='true'
          :actionButton='true'
          @deleted='deleteHandleChange'
          @valueChange='valueChange'
        >
          <template v-slot:remark='props'>
            <a-popover v-if='props.text && model.id && formDisabled' :content='props.text'>
              <div>
                <a-input :value='props.text' :disabled='formDisabled'
                         @change='(e) => remarkInputchange(e,props)'></a-input>
              </div>
            </a-popover>
            <a-input :value='props.text' :disabled='formDisabled' @change='(e) => remarkInputchange(e,props)'
                     v-else></a-input>
          </template>
          <template v-slot:cause='props'>
            <a-popover v-if='props.text && model.id && formDisabled' :content='props.text'>
              <div>
                <a-input :value='props.text' :disabled='formDisabled'
                         @change='(e) => causeInputchange(e,props)'></a-input>
              </div>
            </a-popover>
            <a-input :value='props.text' :disabled='formDisabled' @change='(e) => causeInputchange(e,props)'
                     v-else></a-input>
          </template>
        </j-editable-table>
      </a-tab-pane>

    </a-tabs>
    <a-row v-if='showFlowSubmitButton' style='text-align: center;width: 100%;margin-top: 16px;'>
      <a-button @click='handleOk' type='primary'>提 交</a-button>
    </a-row>
  </a-spin>
</template>

<script>
import pick from 'lodash.pick'
import { getAction, httpAction } from '@/api/manage'
import { FormTypes, getRefPromise, VALIDATE_NO_PASSED, validateFormAndTables } from '@/utils/JEditableTableUtil'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import { validateDuplicateValue } from '@/utils/util'

export default {
  name: 'OaReimbursementForm',
  mixins: [JEditableTableMixin],
  components: {},
  data() {
    return {
      model: {
        total: 0
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        auditGrade: {
          rules: [{ required: true, message: '请选择报销分类!' }]
        },
        opportunityName: {
          rules: [{ required: true, message: '请选择商机!' }]
        },
        type: {
          rules: [{ required: true, message: '请选择报销类别!' }]
        },
        projectName: {
          rules: [{ required: true, message: '请选择项目!' }]
        }
      },
      refKeys: ['oaReimbursementItems'],
      tableKeys: ['oaReimbursementItems'],
      activeKey: 'oaReimbursementItems',
      // 报销单项目
      oaReimbursementItemsTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '报销项目',
            required: true,
            key: 'item',
            type: FormTypes.select,
            dictCode: 'hf_oa_reimbursement_items_item',
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '金额',
            required: true,
            key: 'amount',
            type: FormTypes.input,
            width: '120px',
            placeholder: '${title}',
            defaultValue: '',
            validateRules: [{ required: true, pattern: 'money', message: '${title}不能为空，并且只能为数字' }]
          },
          {
            title: '票据类型',
            required: true,
            key: 'billType',
            type: FormTypes.select,
            dictCode: 'hf_oa_reimbursement_items_billType',
            width: '100px',
            placeholder: '${title}',
            defaultValue: '1',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '事由',
            required: true,
            key: 'cause',
            type: FormTypes.slot,
            slotName: 'cause',
            width: '200px',
            placeholder: '${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '发生日期',
            key: 'happenDate',
            type: FormTypes.date,
            width: '150px',
            placeholder: '${title}',
            defaultValue: ''
          },
          {
            title: '票据张数',
            key: 'billSum',
            type: FormTypes.inputNumber,
            width: '100px',
            placeholder: '${title}',
            defaultValue: '1'
          },
          // {
          //   title: '备注',
          //   key: 'remark',
          //   type: FormTypes.input,
          //   width:"200px",
          //   placeholder: '${title}',
          // },
          {
            title: '备注',
            key: 'remark',
            type: FormTypes.slot,
            width: '200px',
            placeholder: '${title}',
            slotName: 'remark'
          }
          /*       {
              title: '起程',
              key: 'departure',
              type: FormTypes.input,
              width:"120px",
              placeholder: '${title}',
              defaultValue:'',
            },
            {
              title: '到达',
              key: 'arrive',
              type: FormTypes.input,
              width:"150px",
              placeholder: '${title}',
              defaultValue:'',
            },*/
        ]
      },
      url: {
        add: '/oa/oaReimbursement/add',
        edit: '/oa/oaReimbursement/edit',
        queryById: '/oa/oaReimbursement/queryById',
        oaReimbursementItems: {
          list: '/oa/oaReimbursement/queryOaReimbursementItemsByMainId'
        }
      },
      fields: [
        'code',
        'type',
        'opportunityId',
        'remark',
        'total',
        'bpmStatus',
        'createBy',
        'sysOrgCode',
        'issue',
        'opportunityNum',
        'shortName',
        'projectId',
        'opportunityName',
        'projectName',
        'auditGrade',
        'createTime'
      ],
      typeDictText: '',
      storeData: new Map()
    }
  },
  props: {
    //流程表单data
    formData: {
      type: Object,
      default: () => {
      },
      required: false
    },
    //表单模式：false流程表单 true普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    }
  },
  created() {
    //如果是流程中表单，则需要加载流程表单data
    this.showFlowData()
    this.initData()
  },
  mounted() {
  },
  methods: {
    handleOk() {
      const that = this
      return new Promise(((resolve, reject) => {
        /** 触发表单验证 */
        this.getAllTable().then(tables => {
          /** 一次性验证主表和所有的次表 */
          return validateFormAndTables(this.form, tables)
        }).then(allValues => {
          if (typeof this.classifyIntoFormData !== 'function') {
            throw this.throwNotFunction('classifyIntoFormData')
          }
          let formData = this.classifyIntoFormData(allValues)
          // 发起请求
          let url = this.url.add, method = 'post'
          if (this.model.id) {
            url = this.url.edit
            method = 'put'
          }
          that.confirmLoading = true
          httpAction(url, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
              resolve(true)
              that.close()
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
          // return this.request(formData)
        }).catch(e => {
          this.$store.commit('BPM_SUBMIT_STATES', {})
          if (e.error === VALIDATE_NO_PASSED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
      }))

    },

    typeChange(value) {
      this.typeDictText = value
      this.model = {
        ...this.model,
        opportunityId: '',
        opportunityName: '',
        projectId: '',
        projectName: ''
      }
    },
    initData() {
      this.form.setFieldsValue({
        total: 0
      })
    },
    valueChange({ row }) {
      this.storeData.set(row.id, row.amount)
      let total = 0
      this.storeData.forEach(function(value) {
        if (value) {
          total += parseFloat(value)
        }
      })
      total = total.toFixed(2)
      this.form.setFieldsValue({
        total
      })
    },
    deleteHandleChange(ids) {
      var self = this
      ids.forEach((id) => {
        self.storeData.set(id, 0)
      })
      let total = 0
      this.storeData.forEach(function(value) {
        if (value) {
          total += parseFloat(value)
        }
      })
      total = total.toFixed(2)
      this.form.setFieldsValue({
        total
      })
    },
    addBefore() {
      this.form.resetFields()
      this.oaReimbursementItemsTable.dataSource = []
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      let fieldval = pick(this.model, this.fields)
      this.$nextTick(() => {
        this.form.setFieldsValue(fieldval)
      })
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.oaReimbursementItems.list, params, this.oaReimbursementItemsTable)
        this.typeDictText = this.model.type
      }
    },
    causeInputchange(event, props) {
      this.$nextTick(() => {
        let value = event.target.value
        let values = [
          {
            rowKey: props.getValue().id,
            values: {
              remark: props.getValue().remark,
              amount: props.getValue().amount,
              cause: value,
              item: props.getValue().item,
              billSum: props.getValue().billSum,
              billType: props.getValue().billType,
              happenDate: props.getValue().happenDate
            }
          }
        ]
        this.$refs.oaReimbursementItems.setValues(values)
      })
    },
    remarkInputchange(event, props) {
      this.$nextTick(() => {
        let value = event.target.value
        let values = [
          {
            rowKey: props.getValue().id,
            values: {
              remark: value,
              amount: props.getValue().amount,
              cause: props.getValue().cause,
              item: props.getValue().item,
              billSum: props.getValue().billSum,
              billType: props.getValue().billType,
              happenDate: props.getValue().happenDate
            }
          }
        ]
        this.$refs.oaReimbursementItems.setValues(values)
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        oaReimbursementItemsList: allValues.tablesValue[0].values
      }
    },
    //渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId }
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result)
          }
        })
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    popupCallback(row) {
      this.form.setFieldsValue(pick(row, this.fields))
    }
  },
  watch: {
    'oaReimbursementItemsTable.dataSource': {
      deep: true,
      handler: function(value) {
        let total = 0
        var self = this
        value.forEach(function(val) {
          if (val) {
            self.storeData.set(val.id, val.amount)
            total += parseFloat(val.amount)
          }
        })
        total = total.toFixed(2)
        this.form.setFieldsValue({
          total
        })
      }
    },
    '$store.state.bpm.bpmSubmitStates': {
      immediate: true,
      handler(val) {
        if (val && val.edit && val.edit === '1') {
          this.handleOk().then(res => {
            if (res) {
              this.$store.commit('BPM_SUBMIT_STATES', { edit: '2' })
            }
          })
        }
      }
    }
  }
}
</script>

<style scoped>
</style>